<template>
  <a-form
    ref="formRef"
    :model="formState"
    :rules="rules"
    :label-col="labelCol"
    :wrapper-col="wrapperCol"
  >
    <a-form-item label="Edgex服务名" name="edgex_name">
      <a-input v-model:value="formState.edgex_name" />
    </a-form-item>
    <a-form-item label="前缀" name="prefix">
      <a-input v-model:value="formState.prefix" />
    </a-form-item>
    <a-form-item label="后缀" name="extra">
      <a-input v-model:value="formState.extra" />
    </a-form-item>
    <a-form-item label="物理地址" name="location">
      <a-input v-model:value="location.province" placeholder="请输入省" />
      <a-input v-model:value="location.city" placeholder="请输入市" />
    </a-form-item>
    <a-form-item label="描述" name="description">
      <a-textarea v-model:value="formState.description" />
    </a-form-item>
  </a-form>
</template>
<script lang="ts">
import { createEdgex } from "@/controller/Edgex";
import { EdgexAppendForm } from "model";
import {
  defineComponent,
  reactive,
  ref,
  toRaw,
  UnwrapRef,
  watchEffect,
} from "vue";
import message from "ant-design-vue/es/message";
export default defineComponent({
  name: "AppendEdgexForm",
  setup() {
    const formRef = ref();
    const formState: UnwrapRef<EdgexAppendForm> = reactive({
      edgex_name: "",
      prefix: "",
      extra: "",
      location: "",
      description: "",
    });
    const location = reactive({
      province: "",
      city: "",
    });
    watchEffect(() => {
      formState.location = JSON.stringify({
        province: location.province,
        city: location.city,
      });
    });
    const rules = {
      edgex_name: [
        {
          required: true,
          message: "请输入服务名",
          trigger: "blur",
        },
      ],
      prefix: [
        {
          required: true,
          message: "请输入服务前缀",
          trigger: "blur",
        },
      ],
      description: [
        {
          required: true,
          message: "请输入服务描述",
          trigger: "blur",
        },
      ],
    };
    const onSubmit = async () => {
      return await formRef.value
        .validate()
        .then(async () => {
          await createEdgex(toRaw(formState));
          return true;
        })
        .catch(() => {
          message.warn("输入表单不合要求");
          return false;
        });
    };
    return {
      formRef,
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      other: "",
      formState,
      rules,
      onSubmit,
      location,
    };
  },
});
</script>
